<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\DiscountVideoRank;
use App\Model\DiscountVideoUser;
use App\Model\UserProfile;
use App\Model\UserScore;
use App\Model\UserTypeRule;
use App\Util\ComUtil;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\MessageBag;

class DiscountVideoUserController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('特惠视频用户');
            $content->description('');
            $content->body($this->grid());
        });
    }

    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('特惠视频用户-添加');
            $content->description('');
            $content->body($this->form());
        });
    }

    protected function grid()
    {
        return Admin::grid(DiscountVideoUser::class, function (Grid $grid) {
            $grid->model()->orderBy('join_time', 'desc')->with(['userProfile']);
            $grid->join_time('加入时间');
            $grid->user_id('内部ID');
            $grid->userProfile()->user_profile_id('用户ID');
            $grid->userProfile()->nick_name('昵称');
            $grid->userProfile()->avatar('头像')->display(function ($avatar) {
                if (!$avatar) {
                    return '';
                }

                return ComUtil::buidlImgaeHtml($avatar);
            });
            $grid->userScore()->type_id('用户等级')->display(function ($data) {
                if (empty($data)){
                    return '未评级';
                }

                switch ($this->userProfile->gender){
                    case 1:
                        $res = UserScore::MALE_GRADE_TEXT_ARRAY[$data];
                        break;
                    case 0:
                        $res = UserScore::FEMALE_GRADE_TEXT_ARRAY[$data];
                        break;
                }

                return $res ?? '未评级';
            });
            $grid->video_call_time('特惠通话时长（分钟）');
            $grid->video_call_num('特惠通话次数');
            $grid->all_video_call_time('通话总时长');

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
            });

            $grid->filter(function ($filter) {
                $filter->expand();
                 $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('userProfile.user_profile_id', '用户ID');
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->between('join_time', '加入时间')->datetime();
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->between('video_call_time', '特惠分钟数');
                });
            });
        });
    }

    protected function form($mode = '', $id = '')
    {
        return Admin::form(DiscountVideoUser::class, function (Form $form) use ($mode, $id) {
            $form->text('user_id', '女用户ID')->required();

            $form->saving(function (Form $form) {
                $userIds = explode(',', $form->user_id);

                $userProfileIds = UserProfile::getUidByProfileIdV2($userIds);

                $noInsertArr = [];
                foreach ($userIds as $userId) {
                    if (!isset($userProfileIds[$userId])) {
                        $noInsertArr[] = $userId;

                        continue;
                    }

                    if (DiscountVideoUser::getLog($userProfileIds[$userId])) {
                        continue;
                    } else {
                        $insertArr = [
                            'user_id'    => $userProfileIds[$userId],
                            'join_time'  => date('Y-m-d H:i:s'),
                            'user_type'  => UserScore::getUserType((int)$userId),
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                        ];

                        DiscountVideoUser::insert($insertArr);
                    }
                }

                $message = '添加成功';
                if (count($noInsertArr)) {
                    $message = implode(',', $noInsertArr). "不存在";
                }

                $success = new MessageBag([
                    'title'   => '添加成功',
                    'message' => $message,
                ]);

                return redirect('/discount_video_user')->with(compact('success'));
            });
        });
    }

    public function rank()
    {
        $createdAt = request('created_at', date('Y-m-d'));

        $year = (int)date("o", strtotime($createdAt));
        $week = (int)date('W', strtotime($createdAt));

        $where = [
            'week' => $week,
            'year' => $year,
        ];

        $model = DiscountVideoRank::with('userProfile')->where($where)->orderBy('call_time', 'desc')->limit(15)->get()->toArray();

        $info = [];
        foreach ($model as $key => $item) {
            $ranking = ++$key;
            $info[] = [
                'ranking' => $ranking,
                'userId' => $item['user_profile']['user_profile_id'],
                'nickname' => $item['user_profile']['nick_name'],
                'call_time' => $item['call_time'],
                'week' => "第".$item['week'] . "周({$item['year']})",
            ];
        }

        return view('discount_video_rank', ['info' => $info]);
    }
}
